<template>
  <div class="map-page-container">
    <div v-if="currentLocationInfo.isDefault" style="background: #dd1f1f;color: #fff;text-align: center;">
      获取我的位置失败!（浏览器不支持或者定位设备问题）
    </div>
    <van-nav-bar title="地图定位" left-arrow @click-left="$router.back()" class="nav-title" />

    <van-action-sheet
      v-model="showAction"
      :actions="actions"
      cancel-text="取消"
      close-on-click-action
      @select="onSelect"
    />

    <!--<baidu-map class="map"
               :center="currentCenter"
               :zoom="15"
               @ready="handlerMapReady"
    >
      <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
      <bm-marker :position="currentCenter"
                 animation="BMAP_ANIMATION_BOUNCE"
                 :top="true">
      </bm-marker>
    </baidu-map>-->

    <!--<amap class="gaode_amap" :zoom="15" :center="position">
      <amap-marker :position="position" />
    </amap>-->

    <div id="container" class="gaode_amap"></div>

    <van-row type="flex" justify="space-between" class="toolbar_tip" align="center">
      <van-col span="20" class="all_address">
        <div class="detail">{{ destinationPosition.address }}</div>
        <div class="full_address">{{ destinationPosition.FullAddress }}</div>
      </van-col>
      <van-col span="4" style="text-align: right" @click="showAction = true">
        <van-icon name="location" size="40" color="#07C160" />
      </van-col>
    </van-row>
  </div>
</template>

<script>
import Jsonp from 'jsonp'
import {Toast} from 'vant'
import {mapGetters} from 'vuex'
// import {baidu_map_web_js_api} from '../../config/mapConfig';
import {gd_convent_bd} from '../../utils/comTools'

export default {
  name: 'useMap',
  data() {
    return {
      position: [],

      showAction: false,
      // 传过来的坐标值
      destinationPosition: {},
      actions: [
        {id: '0', name: '高德地图'},
        {id: '1', name: '百度地图'},
        {id: '2', name: '腾讯地图'}
      ],

      baiDuCoordinateTrans: []
    }
  },

  created() {
    if (this.$route.query.destinationPosition) {
      this.destinationPosition = JSON.parse(this.$route.query.destinationPosition)
    } else {
      Toast.fail('出错了！')
      this.$router.back()
    }
  },

  computed: {
    ...mapGetters(['currentLocationInfo'])
  },

  mounted() {
    const {currentLongitude, currentLatitude} = this.currentLocationInfo
    const {longitude, latitude} = this.destinationPosition
    const convent_destination = gd_convent_bd(longitude, latitude)
    const convent_current = gd_convent_bd(currentLongitude, currentLatitude)
    this.baiDuCoordinateTrans = [convent_current, convent_destination]
    // 渲染地图
    this.$nextTick(() => {
      console.log(this.destinationPosition)
      this.initGaodeMap(this.destinationPosition)
    })
    // console.log("公式计算结果", this.baiDuCoordinateTrans);

    /*const arr = [
          {
            lat: currentLatitude,
            long: currentLongitude,
          },
          {
            lat: latitude,
            long: longitude,
          }
        ];
        const res = await Promise.all([this._baiDuCoordinateTransApi(arr[0]), this._baiDuCoordinateTransApi(arr[1])]);
        console.log("百度接口---转换结果", res);
        this.baiDuCoordinateTrans = res*/
  },

  methods: {
    /*
        // 请求百度接口，转换为百度的经纬度
        _baiDuCoordinateTransApi(item){
          const url = `http://api.map.baidu.com/geoconv/v1/?coords=${item.long},${item.lat}&from=3&to=5&ak=${baidu_map_web_js_api}`;
          // jsonp使用Promise对象
          return new Promise( (resolve, reject) => {
            Jsonp(url, {}, (err, res) => {
              if(!err){
                const data = res
                if (data.status === 0){
                  const result = data.result[0];
                  resolve(result)
                } else {
                  Toast('请求百度地图接口出错---经纬度转换异常！！请联系客服。');
                }
              } else {
                reject(err)
              }
            });
          });
        },
        */

    initGaodeMap(map) {
      // this.position = [this.destinationPosition.longitude, this.destinationPosition.latitude]
      // console.log(this.position)
      // this.position = [31.352859, 118.432941]
      let mapObj = new AMap.Map('container', {
        zoom: 15,
        center: [map.longitude, map.latitude]
      })
      // let marker = new AMap.Marker({
      //   position: this.position
      // })
      // marker.setMap(map)
      // eslint-disable-next-line no-undef
      mapObj.plugin('AMap.Geocoder', function() {
        // eslint-disable-next-line no-undef
        var geocoder = new AMap.Geocoder({
          // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
          city: ''
        })
        var lnglat = [map.longitude, map.latitude]
        geocoder.getAddress(lnglat, function(status, result) {
          if (status === 'complete' && result.info === 'OK') {
            // eslint-disable-next-line no-undef
            let marker = new AMap.Marker({
              // eslint-disable-next-line no-undef
              position: new AMap.LngLat(map.longitude, map.latitude), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
              title: map.address
            })

            // 将创建的点标记添加到已有的地图实例：
            mapObj.add(marker)
            mapObj.setFitView(marker)
            // result为对应的地理位置详细信息
          }
        })
      })
    },

    onSelect(item) {
      const {longitude, latitude, address, FullAddress} = this.destinationPosition
      const {currentLongitude, currentLatitude, currentAddress, currentFullAddress} = this.currentLocationInfo
      this.$copyText(FullAddress + address).then(
        function(e) {
          Toast.success('目的地已复制')
        },
        function(e) {
          Toast.fail('复制出错了')
        }
      )
      // console.log(this.destinationPosition)
      // this.goMapApp(item)

      // todo 唤醒地图app
      let url
      switch (item.id) {
        case '0':
          url = `https://uri.amap.com/navigation?from=${currentLongitude},${currentLatitude},${currentAddress}&to=${longitude},${latitude},${address}&via=&mode=bus&policy=0&src=mypage&coordinate=wgs84&callnative=1`
          // url = `https://uri.amap.com/marker?position=${longitude},${latitude}&name=${address}`;
          // url = `androidamap://navi?sourceApplication=appname&amp;poiname=fangheng&amp;lat=36.547901&amp;lon=104.258354&amp;dev=1&amp;style=2`;
          break
        case '1':
          if (this.baiDuCoordinateTrans.length === 2) {
            // todo 正则获取地址, 开始区域、结束区域提取 和 复制目的地
            url = `http://api.map.baidu.com/direction?origin=latlng:${this.baiDuCoordinateTrans[0].y},${this.baiDuCoordinateTrans[0].x}|name:${currentAddress}&destination=latlng:${this.baiDuCoordinateTrans[1].y},${this.baiDuCoordinateTrans[1].x}|name:${address}&mode=transit&region=西安&output=html&src=webapp.jinpin.app`
          }
          break
        case '2':
          url = `https://apis.map.qq.com/uri/v1/routeplan?type=bus&from=${currentAddress}&fromcoord=${currentLatitude},${currentLongitude}&to=${address}&tocoord=${latitude},${longitude}&policy=1&referer=jinpin_app`
          break
      }

      // 调用url, 进行唤醒
      console.log('当前', url)

      /*
       *
       * 方法1、window.open() 方法用于打开一个新的浏览器窗口
       *
       */

      window.open(url, '_blank')

      /*
       *
       * 方法2、使用JS模拟触发a标签，打开新的页面
       *
       */
      // console.log("前")
      // let el = document.createElement("a");
      // document.body.appendChild(el);
      // // url 是你得到的连接
      // el.href = url;
      // el.target = '_new'; //指定在新窗口打开
      // el.click();
      // document.body.removeChild(el);
      // console.log("后")

      /*
       *
       * 方法3、http://uusama.com/493.html
       *
       */
    }
  }
}
</script>

<style lang="scss" scoped>
.map-page-container {
  width: 100%;
  box-sizing: border-box;
  position: relative;
  height: calc(100vh);

  /deep/ .nav-title {
    border-bottom: 1px solid #dee1e6;
  }

  .map {
    height: calc(100vh - 128px);
    box-sizing: border-box;

    /deep/ .anchorBL {
      display: none;
    }
  }

  .gaode_amap {
    height: calc(100vh - 128px) !important;
    box-sizing: border-box;

    /deep/ .amap-logo {
      display: none !important;
    }

    /deep/ .amap-copyright {
      display: none !important;
    }
  }

  .toolbar_tip {
    position: fixed;
    height: 80px;
    width: 100%;
    box-sizing: border-box;
    font-size: 14px;
    padding: 0 10px;
    background-color: #ffffff;
    bottom: 1px;
    border-top: 1px solid #dee1e6;

    .all_address {
      padding-left: 2px;

      .detail {
        font-weight: bold;
        letter-spacing: 0.2px;
        color: #0e0e0e;
        margin-bottom: 10px;
      }

      .full_address {
        font-size: 12px;
        color: #696969;
        letter-spacing: 0.2px;
      }
    }
  }
}
</style>
